<?php

namespace Admin\Cli\Tasks;

use Admin\Models\cost\CostCharge;
use Admin\Models\cost\CostChargeDetail;
use Admin\Models\cost\CostChargeFlow;
use Admin\Models\cost\XhcostStudcharge;
use Admin\Models\device\XhsysAccountdevicelocked;
use Admin\Models\log\XhlogCommit;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysUserextrapower;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserpower;
use Admin\Models\user\XhsysUserstud;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Tool;
use Helpers\XhException;
use Modules\Charge;
use Modules\School;
use Phalcon\Cli\Task;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\device\XhsysUsertablet;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Services\App;

class MainTask extends Task
{
    public function mainAction()
    {
        echo "Congratulations! You are now flying with Phalcon CLI!";
    }

    public function testAction()
    {
        echo 'testAction';
    }

    public function notFoundAction()
    {
        echo 'Task Or Action Not Found!';
    }

    private function showMsg($msg, $newLine = true)
    {
        echo $msg;
        if ($newLine) {
            echo PHP_EOL;
        }
    }

    /**
     * 根据科目处理各学校应用组，添加教师及应用
     *
     * @param $params ['科目(逗号间隔)', '包名', '组名']
     *
     * create by ck 20180528
     */
    public function tchAppGroupAction($params)
    {
        $key = '_autoCreate';
        $subject = $params[0] ? explode(',', $params[0]) : '';
        $package = $params[1] ?: '';
        $name = $params[2] ?: '';
        $subject or die('缺少科目！');
        $package or die('缺少包名！');
        $name or die('缺少组名！');
        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
        $subjectIds = [];
        foreach ($subject as $subjectName) {
            $subjectId = array_search($subjectName, $subjectEnum);
            if ($subjectId === false) {
                die($subjectName . ' 科目不存在！');
            }
            $subjectIds[] = $subjectId;
        }
        $groupName = $name . $key;

        $this->showMsg('获取应用信息...');
        $appInfo = App::getAppInfoByPackage($package);
        $appInfo = App::getAppInfoById($appInfo['appId']);
        $versionCode = end($appInfo['appVersions'])['versionCode'];
        $this->showMsg($appInfo['name'] . '当前版本号：' . $versionCode);

        $this->showMsg('遍历学校...');
        foreach (XhschoolInfo::getSchoolSupportArray() as $schoolId => $schoolName) {
            $tchIds = $this->modelsManager->createBuilder()
                ->from(['user' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\sys\\XhsysUserTch', 'user.iUserId = tch.iUserId', 'tch')
                ->columns('user.iUserId')
                ->where('user.bDelete = 0 AND user.bHistory = 0 AND user.bDisable = 0 AND user.iUserType = 4')
                ->andWhere('tch.iSubject IN ({subjectIds:array}) AND user.iSchoolId = :schoolId:', ['subjectIds' => $subjectIds, 'schoolId' => $schoolId])
                ->getQuery()->execute()->toArray();
            if (!$tchIds) {
                $this->showMsg($schoolName . ' 无教师，跳过...');
                continue;
            }
            $tchIds = array_column($tchIds, 'iUserId');

            //判读组是否存在，创建组
            $groups = App::getAppGroups(1, 1, [
                'schoolId' => $schoolId,
                'name' => $groupName,
                'userType' => 2
            ])['rows'];
            if ($groups) {
                $groupId = $groups[0]['groupId'];
            } else {
                $groupId = App::createAppGroup($groupName, $schoolId, 2);
                $this->showMsg($schoolName . ' 组创建成功：' . $groupId);
            }

            try {
                //修改组用户
                App::modifyAppGroupUser($groupId, $tchIds);

                //增加应用
                App::addAppGroupApp($groupId, [['packageName' => $package, 'versionCode' => $versionCode]]);
            } catch (XhException $e) {
                $this->showMsg($schoolName . ' 错误：' . $e->getMessage());
                $this->showMsg(json_encode($e->getDescription()));
                continue;
            }
            $this->showMsg($schoolName . '处理成功...');
        }
        $this->showMsg('处理完毕...');
    }

    private function dealCharge(int $year, int $userId, float $receivable, float $received)
    {
        $charge = $this->db->fetchOne("select * from XHCost_Charge where `year` = '{$year}' and userId = {$userId}");
        if ($charge) {
            if ($receivable) {
                $charge['receivable'] += $receivable;
                $charge['chargeNum'] ++;
            }
            if ($received) {
                $charge['received'] += $received;
                $charge['flowNum'] ++;
            }
            $this->db->update('XHCost_Charge', array_keys($charge), array_values($charge));
        } else {
            $charge = [
                'year' => $year,
                'userId' => $userId,
                'receivable' => $receivable,
                'chargeNum' => $receivable ? 1 : 0,
                'received' => $received,
                'flowNum' => $received ? 1 : 0
            ];
            $this->db->insert('XHCost_Charge', array_values($charge), array_keys($charge));
        }
        unset($charge);
    }

    private function getChargeRow()
    {
        static $page = 1, $size = 10000;
        $offset = $size * ($page - 1);
        while (true) {
            $rows = $this->db->fetchAll("select * FROM XHCost_StudCharge
                    WHERE bDelete = 0 AND iSumDues > 0 LIMIT {$offset},{$size}");
            if (!$rows) {
                break;
            }
            foreach ($rows as $row) {
                yield $row;
            }
            unset($rows);
        }
//        while ($row = $query->fetchArray()) {
//            yield $row;
//        }
    }

    public function chargeRecordAction($params = [])
    {
        try {
//            $this->db->begin();
            $temp = new XhcostStudcharge();
            $index = 1;
            $page = $params[0];
            $size = 10000;
            $offset = $size * ($page - 1);
            $rows = $this->db->fetchAll("select * FROM XHCost_StudCharge
                    WHERE bDelete = 0 AND iSumDues > 0 LIMIT {$offset},{$size}");
            $this->showMsg(sprintf('处理第%d页，共%d条数据...', $page, count($rows)));
            foreach ($rows as $row) {
                $temp->assign($row);

//                Charge::importDetail($temp->iChargeYear, $temp->iStudId, $temp->iSumDues, [
//                    'devPrice' => $temp->iDevCost,
//                    'depositPrice' => $temp->iDeposit,
//                    'servicePrice' => $temp->iSerCost,
//                    'serviceStart' => $temp->tStartTime ? strtotime($temp->tStartTime) : 0,
//                    'serviceEnd' => $temp->tExpireTime ? strtotime($temp->tExpireTime) : 0,
//                ]);
//                if ($temp->iSumCost) {
//                    Charge::importFlow(
//                        $temp->iChargeYear,
//                        $temp->iStudId,
//                        $temp->iSumCost,
//                        $temp->tChargeTime ? strtotime($temp->tChargeTime) : 0,
//                        1
//                    );
//                }

                $detail = array_merge([
                    'year' => $temp->iChargeYear,
                    'userId' => $temp->iStudId,
                    'receivable' => $temp->iSumDues
                ], [
                    'devPrice' => $temp->iDevCost,
                    'depositPrice' => $temp->iDeposit,
                    'servicePrice' => $temp->iSerCost,
                    'serviceStart' => $temp->tStartTime ? strtotime($temp->tStartTime) : 0,
                    'serviceEnd' => $temp->tExpireTime ? strtotime($temp->tExpireTime) : 0,
                ]);
                $this->db->insert('XHCost_ChargeDetail', array_values($detail), array_keys($detail));
                if ($temp->iSumCost) {
                    $flow = [
                        'year' => $temp->iChargeYear,
                        'userId' => $temp->iStudId,
                        'receiveNum' => $temp->iSumCost,
                        'receiveTime' => $temp->tChargeTime ? strtotime($temp->tChargeTime) : 0,
                        'sourceType' => 1
                    ];
                    $this->db->insert('XHCost_ChargeFlow', array_values($flow), array_keys($flow));
                }
                $charge = $this->db->fetchOne("select * from XHCost_Charge
                    where `year` = '{$temp->iChargeYear}' and userId = {$temp->iStudId}");
                if ($charge) {
                    if ($temp->iSumDues) {
                        $charge['receivable'] += $temp->iSumDues;
                        $charge['chargeNum'] ++;
                    }
                    if ($temp->iSumCost) {
                        $charge['received'] += $temp->iSumCost;
                        $charge['flowNum'] ++;
                    }
                    $this->db->update(
                        'XHCost_Charge',
                        array_keys($charge),
                        array_values($charge),
                        'id = ' . $charge['id']
                    );
                } else {
                    $charge = [
                        'year' => $temp->iChargeYear,
                        'userId' => $temp->iStudId,
                        'receivable' => $temp->iSumDues,
                        'chargeNum' => $temp->iSumDues ? 1 : 0,
                        'received' => $temp->iSumCost,
                        'flowNum' => $temp->iSumCost ? 1 : 0
                    ];
                    $this->db->insert('XHCost_Charge', array_values($charge), array_keys($charge));
                }
//                $this->showMsg('当前内存：' . memory_get_usage(true));
//                $this->showMsg('当前索引：' . $index++);
            }
            $this->showMsg('执行完毕');
//            $this->db->commit();
        } catch (\Exception $e) {
//            $this->db->rollback();
            die($e->getMessage() . ' Line：' . $e->getLine());
        }
    }

    public function schoolPowerAction()
    {
//        $schoolPowers = $this->db->query('select * from XHSys_User limit 10000')->fetchAll();
//        foreach ($schoolPowers as $row) {
//            echo $row['iUserId'] . PHP_EOL;
//        }
//        $new = [];
//        $schoolPowers = $this->db->query('select * from XHSys_User limit 10000');
//        while ($row = $schoolPowers->fetch()) {
//            $new[] = $row;
//            echo $row['iUserId'] . PHP_EOL;
//        }
//        var_dump(memory_get_peak_usage());
//        die;
        $userPowers = XhsysUserpower::find([
            'columns' => 'iUPUserId,sUExtraView,sUExtraManage',
            'conditions' => 'sUExtraView IS NOT NULL'
        ])->toArray();
        foreach ($userPowers as $userPower) {
            $view = Tool::getValue(json_decode($userPower['sUExtraView'] ?: '{}', true), 'school', []);
            $manage = Tool::getValue(json_decode($userPower['sUExtraManage'] ?: '{}', true), 'school', []);

            foreach (['view', 'manage'] as $target) {
                $extra = new XhsysUserextrapower();
                $extra->iGoal = 1;
                $extra->iGoalId = $userPower['iUPUserId'];
                $extra->sType = 'school';
                $extra->sTarget = $target;
                $extra->bAll = Tool::getValue($$target, 'all') == 'true';
                $extra->mContent = explode(',', Tool::getValue($$target, 'id', ''));
                $extra->save();
            }
        }
        echo 'Done';
    }

    /**
     * 更新备用机学校id
     *
     * create by ck 20171217
     */
    public function tabletSchoolAction()
    {
        echo '开始更新备用机学校id...' . PHP_EOL;
        try {
            $tabletList = $this->db->fetchAll("SELECT iUTId,sDevNumber,sNowReceiverAccount FROM (SELECT * FROM `XHSys_UserTablet` WHERE IFNULL(sNowReceiverAccount, '') <> '' AND bDelete = 0 ORDER BY iUTId DESC) A WHERE IFNULL(iSchoolId, '') = '' GROUP BY sDevNumber");
            echo '成功获取平板列表，共' . count($tabletList) . '条' . PHP_EOL;
            $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
            if (!$oldDB) {
                throw new \Exception('老数据中心连接失败');
            }
            echo '老数据中心连接成功...' . PHP_EOL;
            echo '开始查询日志信息...' . PHP_EOL;
            $success = $error = $miss = 0;
            foreach ($tabletList as $tablet) {
                $loginInfo = $oldDB->fetchOne("select lo_us_id from (select * from login_log where lo_computername = '{$tablet['sDevNumber']}' order by lo_id desc) a limit 1");
                if (!$loginInfo['lo_us_id']) {
                    echo $tablet['sDevNumber'] . ':未找到记录' . PHP_EOL;
                    $miss++;
                    continue;
                }
                $result = $this->db->execute("update XHSys_UserTablet set iSchoolId = (select iSchoolId from XHSys_User where iUserId = '{$loginInfo['lo_us_id']}') where xh_webmanage.XHSys_UserTablet.iUTId = '{$tablet['iUTId']}'");
                if (!$result) {
                    echo $tablet['sDevNumber'] . ':更新失败' . PHP_EOL;
                    $error++;
                    continue;
                }
                echo $tablet['sDevNumber'] . ':成功更新' . PHP_EOL;
                $success++;
            }
            echo '执行结束，记录共' . count($tabletList) . "条，成功执行{$success}条，其中失败{$error}条，未找到{$miss}条";
        } catch (\Exception $e) {
            die('异常退出：' . $e->getMessage());
        }
    }

    /**
     * 更新设备领用状态
     *
     * create by ck 20171217
     */
    public function tabletStatusAction()
    {
        echo '开始处理设备状态...' . PHP_EOL;
        try {
            $logs = XhlogCommit::find([
                'columns' => 'mContent',
                'conditions' => 'sOperate = "returnRegister"'
            ])->toArray();
            echo '获取日志成功，转换设备id...' . PHP_EOL;;
            $ids = [];
            foreach ($logs as $log) {
                $content = json_decode($log['mContent'], true);
                if (isset($content['post']['ids'])) {
                    $ids = array_merge($ids, $content['post']['ids']);
                }
            }
            echo '获取设备id成功，转换设备编号...' . PHP_EOL;
            $tablets = XhsysUsertablet::find([
                'columns' => 'sDevNumber',
                'conditions' => 'iUTId IN ({idArr:array})',
                'bind' => ['idArr' => $ids]
            ])->toArray();
            $tablets = array_column($tablets, 'sDevNumber');
            echo '获取设备编号成功，共' . count($tablets) . '台需处理' . PHP_EOL;
            $tablets = implode("','", $tablets);
            $query = "UPDATE XHSys_UserTablet SET iReceiveStatus = 2 WHERE iUTId IN ( SELECT iUTId FROM ( SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY tReceiveTime DESC ) A WHERE iReceiveStatus = 3 AND sDevNumber NOT IN ('{$tablets}') GROUP BY sDevNumber)";
            echo '执行语句：' . $query . PHP_EOL;
            $result = $this->db->execute($query);
            if (!$result) {
                throw new \Exception('执行失败');
            }
            echo '成功更新' . $this->db->affectedRows() . '条记录';
        } catch (\Exception $e) {
            die('异常退出：' . $e->getMessage());
        }
    }

    /**
     * 教师机处理
     *
     * create by ck 20180412
     */
    public function tabletTeacherAction()
    {
        $this->showMsg('开始处理教师机...');
        try {
            $dbOld = new Mysql(Main::getConfigByName('oldCenterDB'));
            if (!$dbOld) {
                throw new \Exception('老数据中心连接失败');
            }
            $this->showMsg('老数据中心连接成功...');
            $schoolList = XhschoolInfo::getSchoolSupportArray();
            $this->showMsg('获取学校列表成功，共' . count($schoolList) . '所学校...');
            foreach ($schoolList as $schoolId => $schoolName) {
                $this->showMsg("开始处理学校：{$schoolName}({$schoolId})...");
                $tchInfo = $this->db->fetchAll("SELECT iUserId,sUserName,sLogonName,sSelfPhone,iSchoolId FROM XHSys_User WHERE iUserType = 4 AND bCompany = 0 AND bDisable = 0 AND bDelete = 0 AND bHistory = 0 AND iSchoolId = :schoolId", 2, ['schoolId' => $schoolId]);
                if (!$tchInfo) {
                    $this->showMsg('无教师记录，跳过...');
                    continue;
                }
                $tchInfo = array_column($tchInfo, null, 'iUserId');
                $tchIds = array_keys($tchInfo);

                //查找绑定设备列表
                $bindDev = XhsysAccountdevicelocked::find([
                    'columns' => 'iUserId,sLogonName,sDeviceNumber,sMac,sModel',
                    'conditions' => 'bDelete = 0 AND iSourceType = 1 AND iUserId IN ({idArr:array})',
                    'bind' => ['idArr' => $tchIds]
                ])->toArray();
                $this->showMsg('绑定设备数为：' . count($bindDev));

                //遍历绑定列表，写入为教师机
                $this->showMsg('处理绑定教师...');
                foreach ($bindDev as $dev) {
                    $checkBack = XhsysUsertablet::count([
                        'conditions' => 'bDelete = 0 AND sDevNumber = :devNumber:',
                        'bind' => ['devNumber' => $dev['sDeviceNumber']]
                    ]);
                    if ($checkBack) {
                        $this->showMsg($dev['sDeviceNumber'] . '为备用机或已有记录，跳过...');
                        continue;
                    }
                    $tchDev = new XhsysUsertablet();
                    $tchDev->sReceiverName = $tchInfo[$dev['iUserId']]['sUserName'];
                    $tchDev->sReceiverAccount = $dev['sLogonName'];
                    $tchDev->sReceiverPhone = $tchInfo[$dev['iUserId']]['sSelfPhone'];
                    $tchDev->iReceivePurpose = 3;
                    $tchDev->tReceiveTime = date('Y-m-d H:i:s');
                    $tchDev->sDevNumber = $dev['sDeviceNumber'];
                    $tchDev->sDevType = $dev['sModel'];
                    $tchDev->sMacAddress = $dev['sMac'];
                    $tchDev->iSchoolId = $tchInfo[$dev['iUserId']]['iSchoolId'];
                    $tchDev->bDone = 0;
                    $tchDev->iReceiveStatus = 2;
                    $tchDev->iSource = 0;
                    $tchDev->iBuyType = 1;
                    if (!$tchDev->save()) {
                        $this->showMsg($dev['sDeviceNumber'] . '保存失败...');
                    }
                }

                //筛选无绑定教师
                $this->showMsg('处理未绑定教师...');
                $bindTchIds = array_column($bindDev, 'iUserId');
                $unbindTchIds = array_diff($tchIds, $bindTchIds);
                if (!$unbindTchIds) {
                    $this->showMsg('无记录，跳过...');
                    continue;
                }
                $loginDev = $dbOld->fetchAll('SELECT * FROM (SELECT lo_us_id AS iUserId,lo_uid AS sLogonName,lo_computername AS sDeviceNumber,lo_mac AS sMac,lo_model AS sModel,count(lo_id) AS loginCount FROM login_log WHERE lo_us_id IN (' . implode(',', $unbindTchIds) . ') GROUP BY lo_computername ORDER BY loginCount DESC) a GROUP BY iUserId');
                foreach ($loginDev as $dev) {
                    $checkBack = XhsysUsertablet::count([
                        'conditions' => 'bDelete = 0 AND sDevNumber = :devNumber:',
                        'bind' => ['devNumber' => $dev['sDeviceNumber']]
                    ]);
                    if ($checkBack) {
                        $this->showMsg($dev['sDeviceNumber'] . '为备用机或已有记录，跳过...');
                        continue;
                    }
                    //检查设备是否有学生端登陆记录
                    $studLogin = $dbOld->fetchOne("select count(*) as count from login_log where lo_user_agent = 'com.xuehai.launcher' and lo_computername = '{$dev['sDeviceNumber']}'")['count'];
                    if ($studLogin) {
                        $this->showMsg($dev['sDeviceNumber'] . '含学生端登陆记录，跳过...');
                    }
                    $tchDev = new XhsysUsertablet();
                    $tchDev->sReceiverName = $tchInfo[$dev['iUserId']]['sUserName'];
                    $tchDev->sReceiverAccount = $dev['sLogonName'];
                    $tchDev->sReceiverPhone = $tchInfo[$dev['iUserId']]['sSelfPhone'];
                    $tchDev->iReceivePurpose = 3;
                    $tchDev->tReceiveTime = date('Y-m-d H:i:s');
                    $tchDev->sDevNumber = $dev['sDeviceNumber'];
                    $tchDev->sDevType = $dev['sModel'];
                    $tchDev->sMacAddress = $dev['sMac'];
                    $tchDev->iSchoolId = $tchInfo[$dev['iUserId']]['iSchoolId'];
                    $tchDev->bDone = 0;
                    $tchDev->iReceiveStatus = 2;
                    $tchDev->iSource = 0;
                    $tchDev->iBuyType = 1;
                    if (!$tchDev->save()) {
                        $this->showMsg($dev['sDeviceNumber'] . '保存失败...');
                    }
                }
            }
            $this->showMsg('处理完毕...');
        } catch (\Exception $e) {
            die('异常退出：' . $e->getLine() . '|' . $e->getMessage() . '|' . $e->getTraceAsString());
        }
    }

    public function fixAccountAction()
    {
        $this->showMsg('开始处理异常账号...');
        $dbName = '';
        $error = [];
        try {
            $oldConfig = Main::getConfigByName('oldCenterDB');
            $oldConfig['username'] = 'webmail_user';
            $oldConfig['password'] = 'szw_webmail1234';
            $oldDB = new Mysql($oldConfig);
            if (!$oldDB) {
                throw new \Exception('老数据中心连接失败');
            }
            $this->showMsg('获取日志...');
            $logs = $this->db->fetchAll("SELECT iCommitId,mContent FROM XHLog_Commit WHERE sOperate='importChargeFile' AND tCreateDate >='2017-12-26 00:00:00' AND tCreateDate <= '2017-12-29 14:19:00'");
            foreach ($logs as $log) {
                $content = json_decode($log['mContent'], true);
                if ($content['post']['type'] != 1) {
                    continue;
                }
                $this->showMsg("处理学校id：{$content['post']['schoolId']}...");
                $schoolDB = Main::getSchoolMainDB($content['post']['schoolId'], $dbName);
                if (!$schoolDB) {
                    $this->showMsg('连接失败！！！');
                    $error[] = ['commitId' => $log['iCommitId'], 'error' => '学校数据库连接失败'];
                    continue;
                }
                $newUser = isset($content['detail']['newUser']) ? $content['detail']['newUser'] : [];
                $errorUser = isset($content['detail']['errorData']) ? $content['detail']['errorData'] : [];
                foreach ($newUser as $user) {
                    $result = $schoolDB->execute("delete from users where us_id = '{$user['id']}'");
                    if ($result) {
                        $this->showMsg($user['id'] . '删除成功');
                    }
                    $userInfo = $oldDB->fetchOne("select * from users where us_uid = '{$user['code']}'");
                    if (!$userInfo) {
                        $this->showMsg('找不到该用户：' . $user['code']);
                        continue;
                    }
                    $result = $schoolDB->insert('users', array_values($userInfo), array_keys($userInfo));
                    if ($result) {
                        $this->showMsg($user['code'] . '插入成功');
                    }
                }
                foreach ($errorUser as $user) {
                    if (strpos($user['reason'], '创建失败') === false) {
                        continue;
                    }
                    $userInfo = $oldDB->fetchOne("select * from users where us_uid = '{$user['code']}'");
                    if (!$userInfo) {
                        $this->showMsg('找不到该用户：' . $user['code']);
                        continue;
                    }
                    $result = $schoolDB->insert('users', array_values($userInfo), array_keys($userInfo));
                    if ($result) {
                        $this->showMsg($user['code'] . '插入成功');
                    }
                }
            }
            if ($error) {
                $this->showMsg('学校连接失败：');
                $this->showMsg(json_encode($error));
            }
            $this->showMsg('执行完毕');
        } catch (\Exception $e) {
            die('异常退出：' . $e->getMessage() . ' Line:' . $e->getLine());
        }
    }

    public function getBookAction()
    {
        $schEnum = [
            'iStatus' => [1 => '同步书', 8 => '专题书', 9 => '引用书'],
        ];
        $fileName = CACHE_PATH . 'book.txt';
//        var_dump($fileName);

//        $dictionaries = new Dictionaries();
//        $dictionariesArr = $dictionaries->runDictionariesData();
//        $getArr = array(
//            'page' => 1,
//            'size' => 10000,
//            'userId' => 0,
////            'libraryType' => $status ? $status : 1,
//            'publishStatus' => '0',
//        );
//        $this->showMsg('开始从接口获取数据');
//        $books = new Books();
//        $result = $books->getAllBookList($getArr);
//        $this->showMsg('结束从接口获取数据');
//        $data = [];
//        if (!empty($result)) {
//            $total = count($result['bookClientDTOList']);
//            $this->showMsg('开始获取云教辅数据，共：' . $total . '条数据');
//            foreach ($result['bookClientDTOList'] as $value) {
//                $books = new Books();
//                $bookResult = $books->getBookDetail($value['bookId']);
//                if ($bookResult['bookNature'] == 1) {
//                    $data[] = array(
//                        'bookId' => $value['bookId'],
//                        'bookName' => $value['bookName'],
//                        'count' => $value['count'],
//                        'libraryType' => $schEnum['iStatus'][$value['libraryType']],
//                        'grade' => $dictionariesArr['grade'][$value['gradeId']] ?? '',
//                        'subject' => $dictionariesArr['subject'][$value['subjectId']] ?? '',
//                        'textBookVersion' => $dictionariesArr['textBookVersion'][$value['textBookVersion']] ?? '',
//                    );
//                }
//            }
//            $this->showMsg('结束获取云教辅数据');
//        }
        $data = file_get_contents(CACHE_PATH . 'bookData.txt');
        $data = json_decode($data, true);
        if ($data) {
//            file_put_contents(CACHE_PATH . 'bookData.txt', json_encode($data), FILE_APPEND);
            $dataTotal = count($data);
            $this->showMsg('开始处理数据，共：' . $dataTotal . '条数据');
            foreach ($data as &$datum) {
                $paramsArr = array(
                    'bookId' => $datum['bookId'],
                    'page' => 1,
                    'size' => 10000,
                );
                $datum['tchNum'] = 0;
                $teach = [];
//                $questionPrivilege = new QuestionPrivilege();
//                $result = $questionPrivilege->getBookScopeUser($paramsArr);
                $httpClient = new HttpClient('https://admin.yunzuoye.net');
                $request = [
                    'url' =>
                        'http://resmgmt.xhi.net/api/v1/userBookPowers/scopeType',
                    'method' => 'get',
                    'body' => $paramsArr
                ];
                $result = $httpClient->postJson('other/transferInterface', $request);
                if (!empty($result)) {
                    $result = json_decode($result->body, true);

                    $users = [];
                    $datum['tchNum'] = $result['totalCount'];
                    if (isset($result['userDTOList']) && count($result['userDTOList']) > 0) {
                        $ids = array_column($result['userDTOList'], 'userId');
                        $builder = $this->modelsManager->createBuilder()
                            ->columns('u.iUserId,u.iSchoolId,t.iSubject,t.iCurGrade')
                            ->from(['u' => 'Admin\\Models\\user\\XhsysUser'])
                            ->leftJoin('Admin\\Models\\sys\\XhsysUserTch', 't.iUserId=u.iUserId', 't')
                            ->where('u.bDelete= 0  AND u.iUserId in ({ids:array})  ', ['ids' => $ids]);
                        $users = $builder->getQuery()->execute()->toArray();
                        $users = array_column($users, null, 'iUserId');
                    }

                    $schools = XhschoolInfo::getSchoolSupportArray(true);
                    foreach ($result['userDTOList'] as $value) {
                        $user = isset($users[$value['userId']]) ? $users[$value['userId']] : '';
                        $schoolId = isset($user['iSchoolId']) ? $user['iSchoolId'] : '';
                        $teach[] = array(
                            'tchId' => $value['userId'],
                            'tchName' => $value['userName'],
                            'schoolId' => $schoolId,
                            'schoolName' => isset($schools[$schoolId]) ? $schools[$schoolId] : '',
                        );
                    }
                }
                $datum['tchList'] = $teach;
            }
            $this->showMsg('结束处理数据');
            foreach ($data as $key => $fina) {
                $this->showMsg('开始插入第' . $key . '条数据：');
                file_put_contents($fileName, json_encode($fina) . PHP_EOL, FILE_APPEND);
            }
            $this->showMsg('插入结束');
        }
    }

    public function bookUseAction()
    {
        $path = CACHE_PATH;
//        $path       = __DIR__ . '/';
        $sourceFile = $path . 'book.txt';
        $targetFile = $path . 'bookUse.txt';
        $startTime  = strtotime('2018-09-01');
        $endTime    = time();
        $httpClient = new HttpClient('https://admin.yunzuoye.net');

        $bookList = file($sourceFile);
        $success  = 0;
        foreach ($bookList as $book) {
            $book = json_decode($book);
            $this->showMsg(sprintf('开始处理书本:%s,书id:%s...', $book->bookName, $book->bookId));
            $request = [
                'url' => sprintf(
                    'http://cloudwkstatic.xhi.net/intranet/work/statistic/schools/0/books/%s/',
                    $book->bookId
                ),
                'method' => 'get',
                'body' => ['startTime' => $startTime, 'endTime' => $endTime]
            ];
            $response = $httpClient->postJson('other/transferInterface', $request);
            if (!$response->isSuccess()) {
                $this->showMsg('获取信息失败:' . $response->body);
                continue;
            }
            $tchList = array_column($book->tchList, null, 'tchId');
            foreach ($response->toArray() as $row) {
                $tchList[$row['teacherId']] = array_merge($tchList[$row['teacherId']] ?? [], $row);
            }
            $book->tchList = array_values($tchList);
            file_put_contents($targetFile, json_encode($book, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            $this->showMsg('处理成功!');
            $success++;
        }
        $this->showMsg(sprintf('执行完毕,共处理%d条,成功%d条!', count($bookList), $success));
    }

    public function bookUseExcelAction()
    {
//        $path       = __DIR__ . '/';
        $path       = CACHE_PATH;
        $sourceFile = $path . 'bookUse.txt';
        $bookList   = file($sourceFile);

        try {
            $objPHPExcel = new Spreadsheet();
            $objPHPExcel->setActiveSheetIndex(0);
            $sheet = $objPHPExcel->getActiveSheet();

            //把数据循环写入excel中
            $key = 0;
            foreach ($bookList as $book) {
                $book = json_decode($book);
                $sheet->setCellValue('A' . ++$key, $book->bookName);
                $sheet->setCellValue('B' . $key, $book->libraryType);
                $sheet->setCellValue('C' . $key, $book->subject);
                $sheet->setCellValue('D' . $key, $book->textBookVersion);
                $sheet->setCellValue('E' . $key, '题数:' . $book->count);

                $sheet->setCellValue('A' . ++$key, $book->bookId);
                $sheet->setCellValue('B' . $key, '总布置:' . array_sum(array_column($book->tchList, 'workTimes')));
                $sheet->setCellValue('C' . $key, '关联教师:' . $book->tchNum);
                $sheet->setCellValue('D' . $key, '使用教师:' . count(array_filter(array_column($book->tchList, 'workTimes'))));

                $sheet->setCellValue('A' . ++$key, '使用情况:');
                $sheet->setCellValue('B' . $key, '姓名');
//                $sheet->setCellValue('C' . $key, '学校');
                $sheet->setCellValue('C' . $key, '布置次数');
                $sheet->setCellValue('D' . $key, '总题数（去重）');
                $sheet->setCellValue('E' . $key, '总题数（不去重）');
                $sheet->setCellValue('F' . $key, '最后布置');
                foreach ($book->tchList as $tch) {
                    $sheet->setCellValue('B' . ++$key, $tch->tchName ?? $tch->teacherName);
//                    $sheet->setCellValue('C' . $key, $tch->schoolName ?? '');
                    $sheet->setCellValue('C' . $key, $tch->workTimes ?? '');
                    $sheet->setCellValue('D' . $key, $tch->topicNum ?? '');
                    $sheet->setCellValue('E' . $key, $tch->topicsRepeatNum ?? '');
                    $sheet->setCellValue('F' . $key, isset($tch->lastTime) ? date('Y-m-d H:i:s', substr($tch->lastTime, 0, 10)) : '');
                }
                $key++;
            }

            //导出代码
            $objWriter = new Xlsx($objPHPExcel);
            $objWriter->save(CACHE_PATH . 'stats.xlsx');
            return true;
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }
}
